package com.mtw.bbs.common.jdbcBase.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.google.common.reflect.ClassPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class SqlGenerator1 {


    public static void main(String[] args) {
        SqlGenerat("com.mtw.bbs.comment.pojo.entity");
    }

    private static final Logger logger = LoggerFactory.getLogger(SqlGenerator1.class);

    /**
     * 用来存储Java等属性类型与sql中属性类型的对照
     * </br>
     * 例如：java.lang.Integer 对应 integer
     */
    public static Map<String, String> map = new HashMap<>();

    static {

        map.put("java.lang.String", "varchar(255)");
        map.put("java.lang.Integer", "int");
        map.put("java.lang.Long", "integer unsigned");
        map.put("java.lang.byte[]", "blob");
        map.put("java.lang.Boolean", "bit");
        map.put("java.math.BigInteger", "bigint unsigned");
        map.put("java.lang.Float", "float");
        map.put("java.lang.Double", "double");
        map.put("java.sql.Date", "datetime");
        map.put("java.sql.Time", "time");
        map.put("java.sql.Timestamp", "datetime");
        map.put("java.util.Date", "datetime");
        map.put("java.time.LocalDateTime", "datetime");
        map.put("java.time.LocalDate", "date");
        map.put("java.time.LocalTime", "time");
        map.put("java.lang.Byte", "tinyint");
        map.put("java.math.BigDecimal", "decimal");
    }

    public static void SqlGenerat(String packageName){
        //生成sql的文件夹
        String filePath = "E:/my/mbbs/sql/like";
        //开始构造sql
        sqlConstruction(packageName, filePath);
    }



    /**
     * 生成sql建库语句
     * @param packageName 实体类所在的package在磁盘上的绝对路径
     * @param filePath 生成sql的文件夹
     */
    private static void sqlConstruction(String packageName, String filePath) {

        StringBuffer sqls = new StringBuffer();
        //获取包下的所有类名称
        List<Class> list = getClass(packageName);
        for (Class clz : list) {
            String sql = generateSql(clz);
            sqls.append(sql);
        }
        StringToSql(sqls.toString(), filePath + ".sql");
    }

    /**
     * 根据实体类生成建表语句
     *
     */
    public static String generateSql(Class<?> clz) {

        // 类名
        String tableName =  clz.getAnnotation(TableName.class).value();
        String PRIMARYKEY = "";


        /*超类字段数组*/
        Field[] superclassFields = clz.getSuperclass().getDeclaredFields();

        Field[] fields = clz.getDeclaredFields();
        StringBuffer column = new StringBuffer();

        String PRIMARYKEY_char = " CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,";
        String varchar = " CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,";
        for (Field f : fields) {

            if ("serialVersionUID".equals(f.getName()) ){
                continue;
            }
            if (f.isAnnotationPresent(TableField.class) ) {
                TableField annotation = f.getAnnotation(TableField.class);
                if (!annotation.exist()){
                    continue;
                }
            }

            if (f.isAnnotationPresent(TableId.class)){
                PRIMARYKEY = getStandardFields(f.getName());
                test(column,PRIMARYKEY_char,f);
            }else {
                test(column,varchar,f);
            }


        }
        for (Field sf : superclassFields) {
            if ("serialVersionUID".equals(sf.getName()) ){
                continue;
            }
            if (sf.isAnnotationPresent(TableId.class)){
                PRIMARYKEY = getStandardFields(sf.getName());
                test(column,PRIMARYKEY_char,sf);
            }else {
                test(column,varchar,sf);
            }
        }


        StringBuffer sql = new StringBuffer();
        sql.append("\n")
                .append("\n DROP TABLE IF EXISTS `" + tableName + "`; ")
                .append(" \n CREATE TABLE `" + tableName + "`  (")
                .append(" " + column)
                .append(" \n PRIMARY KEY (`"+ PRIMARYKEY +"`) USING BTREE")
                .append(" \n ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci; \n");
        return sql.toString();
    }

    public static void test(StringBuffer column,String varchar,Field f){

        if ("java.lang.String".equals(f.getType().getName())){
            column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(f.getType().getName())).append(varchar);
        }else {
            column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(f.getType().getName())).append(",");
        }
    }

    /**
     * 转换为标准等sql字段 例如 adminUser → admin_user
     *
     * @param str 转换为字符串的字段名
     * @return
     */
    public static String getStandardFields(String str) {
        StringBuffer sb = new StringBuffer();
        if ("id".equals(str)){
            return str;
        }
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            //非首字母，在大写字母A到Z之间
            if (i != 0 && (c >= 'A' && c <= 'Z')) {
                sb.append("_");
            }
            sb.append(String.valueOf(c).toLowerCase());
        }
        return sb.toString();
    }


    public static List<Class> getClass(String packageName){
        List<Class> result = new ArrayList<>();
        try {
            result = ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses()
                    .stream()
                    .filter(c->c.getPackageName().equals(packageName))
                    .map(c ->c.load()).collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("read class error",e);
        }
        return result;
    }

    /**
     * 将生成等String字符串 写进sql文件
     *
     * @param str  String字符串
     * @param path sql文件路径路径
     */
    public static void StringToSql(String str, String path) {

        BufferedWriter bw = null;
        try {
            //文件路径（路径+文件名）
            File file = new File(path);
            //文件不存在则创建文件，先创建目录
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }


            bw = new BufferedWriter(new FileWriter(path, true));
            bw.write(str);
            System.out.println("生成成功!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭文件输出流
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
